package com.zhangx.study.demo.forkjoin.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhangx.study.demo.forkjoin.constant.RequestQueue;
import com.zhangx.study.demo.forkjoin.dto.OrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName BatchReqHandle
 * @Description 批量处理类
 * @Author zhangx
 * @Date 2020/6/17 15:26
 **/
@Slf4j
@Service
public class BatchReqHandle {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 定期从队列中取数组织批量请求
     */
    @PostConstruct
    public void init(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
        int delayMillSeconds = 0;
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
//                log.info("定期收集并处理任务");
                List<Map<String,String>> params = new ArrayList<>();
                List<OrderRequest> requests = new ArrayList<>();
                for (int i = 0; i < RequestQueue.queue.size(); i++) {
                    OrderRequest orderRequest = RequestQueue.queue.poll();
                    Map<String, String> param = new HashMap<String, String>();
                    param.put("orderNo", orderRequest.getOrderNo());
                    param.put("id", orderRequest.getId());
                    params.add(param);
                    requests.add(orderRequest);
//                    log.info(JSON.toJSONString(orderRequest));
                }
                if (params.size()>0){
                    call(params,requests);
                }

            }
        }, delayMillSeconds,100, TimeUnit.MILLISECONDS);

    }

    private void call(List<Map<String,String>> params,List<OrderRequest> requests){
        JSONArray result = null;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<List<Map<String,String>>> request = new HttpEntity<>(params, headers);

        ResponseEntity<JSONArray> wcsResp = restTemplate.postForEntity("http://localhost:6060/remote/order/confirm/batch", request, JSONArray.class);
        if (wcsResp.getStatusCodeValue() != 200) {
            log.error("调用接口失败！");
        } else {
            result = wcsResp.getBody();
//            log.info(String.valueOf(result.size()));
            Map<String,JSONObject> respMap = new HashMap<>();
            for (int i = 0; i < result.size(); i++) {
                JSONObject resp = result.getJSONObject(i);
                respMap.put(resp.getString("id"),resp);
            }
            for (OrderRequest req:requests) {
                req.getFuture().complete(respMap.get(req.getId()));
            }
        }
    }

}
